package com.zjxf.utils;

import com.google.common.io.Files;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.Objects;

/**
 * created with IntelliJ IDEA
 *
 * @author: create by limu
 * Date: 2020/8/6
 * Time：14:31
 */
public class RequestUtils {

    /**
     * 获取用户ip
     *
     * @param request 请求参数
     * @return 返回参数
     */
    public static String getIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        String unknown = "unknown";
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 凭空获取Request
     *
     * @return HttpServletRequest
     */
    public static HttpServletRequest getHttpServletRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    /**
     * 下载文件
     *
     * @param file 文件信息
     * @param out  流
     * @throws IOException 流异常
     */
    public static void downFile(File file, OutputStream out) throws IOException {
        byte[] bytes = Files.toByteArray(file);
        out.write(bytes);
        out.close();
    }

    public static void downFile(byte[] bytes, OutputStream out) throws IOException {
        out.write(bytes);
        out.close();
    }

    public static String getOriginalFilename(HttpServletRequest request){
        MultipartHttpServletRequest mureq = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> files = mureq.getFileMap();
        MultipartFile file =null;
        if (files != null &&files.size()> 0) {

            Map.Entry<String, MultipartFile> f = files.entrySet().iterator().next();
            file = f.getValue();
        }
        return file.getOriginalFilename();
    }


}
